package cn.zwk.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DataRow {
    private AbstractItem parent;
    private String key="";
    private double val;
    
    // 便捷构造函数（不包含parent）
    public DataRow(String key, double val) {
        this.key = key;
        this.val = val;
    }
    
    @Override
    public String toString() {
        long timestamp = getTimestamp();
        String keyWithTag = addHostTag(key);
        return String.format("%s %.6f %d", keyWithTag, val, timestamp);
    }
    
    private long getTimestamp() {
        if (parent != null && parent.getParent() != null && parent.getParent().getParent() != null) {
            return parent.getParent().getParent().getTimestamp();
        }
        return System.currentTimeMillis();
    }
    
    private String addHostTag(String originalKey) {
        if (parent != null && parent.getParent() != null && parent.getParent().getParent() != null) {
            String hostName = parent.getParent().getParent().getHostName();
            if (hostName != null && !hostName.isEmpty()) {
                if (originalKey.contains("{") && originalKey.contains("}")) {
                    // 已经有标签，在现有标签内部添加tag
                    int openBraceIndex = originalKey.indexOf("{");
                    int closeBraceIndex = originalKey.lastIndexOf("}");
                    String beforeBrace = originalKey.substring(0, openBraceIndex + 1);
                    String existingLabels = originalKey.substring(openBraceIndex + 1, closeBraceIndex);
                    String afterBrace = originalKey.substring(closeBraceIndex);
                    
                    // 如果现有标签不为空，则在前面加逗号
                    String tagToAdd = existingLabels.isEmpty() ? 
                        "tag=\"" + hostName + "\"" : 
                        "tag=\"" + hostName + "\"," + existingLabels;
                    
                    return beforeBrace + tagToAdd + afterBrace;
                } else {
                    // 没有标签，添加新标签
                    return originalKey + "{tag=\"" + hostName + "\"}";
                }
            }
        }
        return originalKey;
    }
}
